/**
 * 连接webSocket的公共方法
 */

import {ref} from 'vue'
import {Client} from '@stomp/stompjs';
import SockJS from 'sockjs-client';
import {ElMessage} from "element-plus";
import axios from "axios";
import {notify} from "@kyvg/vue3-notification";

//定义全局变量
export const chatIds = ref([]);
export const userId = ref(parseInt(localStorage.getItem('id')));


//创建连接对象
export const socket = new SockJS('http://121.199.30.8:9937/ws');
export const stompClient = new Client({
    webSocketFactory: () => socket,
    debug: function (str) {
        console.log(str);
    }
})

//进行连接
export const connectWebSocket = () => {
    stompClient.onConnect = (frame) => {
        console.log('连接成功' + frame);
        fetchChatIds().then(() => {
            //连接成功后，订阅所有的聊天id
            subscribeToChats();
        })

    }
}
stompClient.activate();
//获取当前用户的所有聊天
export const fetchChatIds = async () => {
    try {
        const response = await axios.get('/chat/getChatIds/' + userId.value);
        chatIds.value = response.data.data || [];
        console.log(chatIds.value)
    } catch (error) {
        ElMessage.error('获取聊天列表失败:', error);
    }
}
// 订阅所有聊天
export const subscribeToChats = () => {
    chatIds.value.forEach(chatId => {
        stompClient.subscribe(`/queue/private/${chatId}`, (message) => {
            const receivedMessage = JSON.parse(message.body);
            console.log(receivedMessage)
            console.log('收到消息，路径:', message.headers.destination);
            console.log('消息内容:', message.body);
            if (receivedMessage.senderId !== userId.value) {
                notify({
                    title: "收到来自" + receivedMessage.senderName + "的1条消息",
                    text: receivedMessage.messageContent,
                    type: 'success',
                    duration: 5000,
                })
            }
            // 显示桌面通知
            if (Notification.permission === 'granted' && receivedMessage.senderId !== userId.value) {
                new Notification(`${receivedMessage.senderName}`, {
                    body: receivedMessage.messageContent
                });
            }
        })
    })
}
